from flask import Blueprint, request, jsonify
from flask_cors import CORS

from dao.UserDao import UserDao

user_blueprint = Blueprint('user', __name__)
CORS(user_blueprint)

# 用户注册接口
@user_blueprint.route('/userRegister', methods=['POST'])
def user_register():
    user_dao = UserDao()
    user_dao.connect()
    username = request.json.get('username')
    password = request.json.get('password')
    existing_user = user_dao.get_user_by_username(username)
    if existing_user:
        response = {'success': False, 'msg': '用户名已存在'}
    else:
        user_dao.insert(username, password)
        response = {'success': True, 'msg': '注册成功'}
    return jsonify(response)

# 用户登录接口
@user_blueprint.route('/userLogin', methods=['POST'])
def user_login():
    username = request.json.get('username')
    password = request.json.get('password')
    user_dao = UserDao()
    user_dao.connect()
    user_info = user_dao.get_user_by_username(username)
    if user_info and len(user_info) > 0:
        stored_password = user_info[0][2]
        if password == stored_password:
            response = {'success': True, 'msg': '登录成功'}
        else:
            response = {'success': False, 'msg': '密码错误'}
    else:
        response = {'success': False, 'msg': '用户不存在'}
    return jsonify(response)
